import { Context, h } from 'koishi';
import { resizeImageToBase64 } from './utils';

export interface ImageDetectResult{
    channelId: string;
    channelName: string;
    userId: string;
    userName: string;
    timeString: string;
    imageUrl: string;
    detectResult: {
        predicted_class: string;
        probabilities: {
            [category: string]: number;
        };
    }
}

export class KookCard{
    static ImageDetectResultCard(result:ImageDetectResult){
        return{
            "type": "card",
            "theme": "secondary",
            "size": "lg",
            "modules": [
              {
                "type": "section",
                "text": {
                  "type": "paragraph",
                  "cols": 2,
                  "fields": [
                    {
                      "type": "kmarkdown",
                      "content": `**群号**\n${result.channelId}`
                    },
                    {
                      "type": "kmarkdown",
                      "content": `**群名**\n活动中心${result.channelName}`    
                    }
                  ]
                }
              },
              {
                "type": "section",
                "text": {
                  "type": "paragraph",
                  "cols": 2,
                  "fields": [
                    {
                      "type": "kmarkdown",
                      "content": `**qq号**\n${result.userId}`
                    },
                    {
                      "type": "kmarkdown",
                      "content": `**qq名**\n${result.userName}`
                    }
                  ]
                }
              },
              {
                "type": "divider"
              }
            ]
          }
    }
}

export async function getImageDetectResultCardMsg(ctx:Context ,result: ImageDetectResult){
  let msg_res = '';

  const imageBase64 = await resizeImageToBase64(ctx, result.imageUrl);
  
  msg_res += "==================\n\n";
  msg_res += "图片检测结果:\n";
  msg_res += `\t群号: \t${result.channelId}\n`;
  msg_res += `\t群名: \t${result.channelName}\n`;
  msg_res += `\tqq号: \t${result.userId}\n`,
  msg_res += `\tqq名: \t${result.userName}\n`
  msg_res += `\t时间: \t${result.timeString}\n`;
  msg_res += "----------\n"
  // msg_res += `图片：${h.image(result.imageUrl)}\n`;
  msg_res += `图片：${h.image(imageBase64)}\n`;
  msg_res += `\t检测信息：\n`
  msg_res += `\t\tpredicted_class:\n\t\t\t${result.detectResult.predicted_class}`;
  msg_res += `\t\tprobabilities:\n${
    Object.entries(result.detectResult.probabilities)
      .map(
        // ([k,v]) => `\t\t\t${k}: \t${v}`
        ([k,v]) => {
          const maxProbability = Math.max(...Object.values(result.detectResult.probabilities));
          const emoji = v === maxProbability ? '🥇' : '🥈'; // 概率最大时用金牌，否则用银牌
          return `\t\t\t${emoji} ${k}: \t${v.toFixed(4)}`;
        }
      )
      .join('\n')
  }\n`;
  msg_res += "==================\n\n";

  return msg_res;
}